home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2390 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: 21 Jan 1996 01:02:49 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4ds3bp$k5m@castle.nando.net>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>   <4dp8cr$sit@crl.crl.com>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: grail1007.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4dp8cr$sit@crl.crl.com>, bobfry@crl.com (Robert Fry) writes:
  14. >Someone was asking for a quick way to determine if a number is a power of 
  15. >2. The solutions I've seen involved ounting every bit and seeing if the 
  16. >number of 'on' bits is 1. But why not take advantage of the binary 
  17. >representation of numbers and use:
  18. >int is_power_of_2( long num)
  19. >{
  20. >    return((( num - 1) & num) == 0);
  21. >}
  22.  
  23. You don't really want signed do you?  And is zero a power
  24. of 2?  (maybe pow(2,-inf)?)  How about:
  25.  
  26. int is_power_of_2( unsigned long n )
  27. {
  28.    return !(n - 1 & n) && n != 0;
  29. }
  30.  
  31. Bill McCarthy
  32. actuary@nando.net
  33. Wendell, NC  USA
  34.